import type { EventHandlerRequest, H3Event } from 'h3';

export function wrapResponse<T>(context: H3Event<EventHandlerRequest>, data: T, code: number = 200, message?: string, success?: boolean): ResponseBody<T> {
  let resMsg: string;
  const statusCode = context.node.res.statusCode || code || 500;

  if (context.node.res.statusMessage) {
    resMsg = context.node.res.statusMessage;
  }
  else if (message) {
    resMsg = message;
  }
  else if (statusCode in RESPONSE_CODE_MAP) {
    resMsg = RESPONSE_CODE_MAP[statusCode];
  }
  else {
    resMsg = 'OK';
  }

  setResponseStatus(context, code, resMsg);
  let flag: boolean;
  if (success === undefined) {
    flag = code >= 200 && code < 300;
  }
  else {
    flag = success;
  }

  return {
    success: flag,
    status: code,
    message: resMsg,
    result: data,
    timestamp: Date.now(),
  };
}

export function wrapError(error: any, code: number = 500, message?: string): ResponseBody {
  return {
    success: false,
    status: code,
    message: message || error.message || 'Internal Server Error',
    timestamp: Date.now(),
  };
}
